<?php

namespace App\Http\Middleware;

use App\Http\Response\JsonResult;
use App\Http\Response\ResponseCode;
use Closure;
use Illuminate\Http\JsonResponse;

class ApiReturnResultMiddle
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $result =  $next($request);

        if ( $result instanceof  JsonResponse ) {
            $data = $result->getData() ;
            if ( isset($data->code) && $data->code != ResponseCode::SUCCESS ) {
                return $result;
            } else {
                return JsonResult::returnJson(ResponseCode::SUCCESS,$data);
            }
        }

        if ( is_array($result) ) {
            return JsonResult::returnJson(ResponseCode::SUCCESS,$result);
        }

        return $result;
    }
}
